<template>
  <div class="my-orders">
    <!-- 订单统计 -->
    <div class="order-stats">
      <h2>我的订单</h2>
      <div class="stats-grid">
        <div class="stat-item">
          <div class="stat-value">{{ stats.total || 0 }}</div>
          <div class="stat-label">总订单</div>
        </div>
        <div class="stat-item">
          <div class="stat-value">{{ stats.paid || 0 }}</div>
          <div class="stat-label">已支付</div>
        </div>
        <div class="stat-item">
          <div class="stat-value">{{ stats.pending || 0 }}</div>
          <div class="stat-label">待支付</div>
        </div>
        <div class="stat-item">
          <div class="stat-value">{{ stats.cancelled || 0 }}</div>
          <div class="stat-label">已取消</div>
        </div>
      </div>
    </div>

    <!-- 订单列表 -->
    <div class="orders-list">
      <div class="filter-bar">
        <div class="filter-group">
          <label>状态筛选：</label>
          <select v-model="statusFilter" @change="loadOrders">
            <option value="all">全部</option>
            <option value="paid">已支付</option>
            <option value="pending">待支付</option>
            <option value="cancelled">已取消</option>
          </select>
        </div>
      </div>

      <div v-if="loading" class="loading">加载中...</div>
      
      <div v-else-if="orders.length === 0" class="empty-state">
        <p>暂无订单</p>
        <button class="btn-primary" @click="goToReservation">立即预约</button>
      </div>

      <div v-else class="orders-container">
        <div 
          v-for="order in orders" 
          :key="order.id"
          class="order-card"
          :class="{
            'status-paid': order.status === 'paid',
            'status-pending': order.status === 'pending',
            'status-cancelled': order.status === 'cancelled'
          }"
        >
          <div class="order-header">
            <div class="order-info">
              <h3>{{ order.scenicSpotName }}</h3>
              <span class="order-id">订单号：{{ order.id }}</span>
            </div>
            <div class="order-status">
              <span :class="`status-badge status-${order.status}`">
                {{ getStatusText(order.status) }}
              </span>
            </div>
          </div>

          <div class="order-details">
            <div class="detail-item">
              <span class="label">参观日期：</span>
              <span class="value">{{ order.visitDate }} {{ order.visitTime }}</span>
            </div>
            <div class="detail-item">
              <span class="label">游客信息：</span>
              <span class="value">{{ order.visitorName }} ({{ order.visitorPhone }})</span>
            </div>
            <div class="detail-item">
              <span class="label">票型：</span>
              <span class="value">{{ order.ticketType }} × {{ order.visitorCount }}</span>
            </div>
            <div class="detail-item">
              <span class="label">总金额：</span>
              <span class="value price">¥{{ order.totalAmount }}</span>
            </div>
            <div v-if="order.paymentTime" class="detail-item">
              <span class="label">支付时间：</span>
              <span class="value">{{ formatDateTime(order.paymentTime) }}</span>
            </div>
          </div>

          <div class="order-actions">
            <button 
              v-if="order.status === 'pending'"
              class="btn-primary"
              @click="payOrder(order)"
            >
              立即支付
            </button>
            <button 
              v-if="order.status === 'pending'"
              class="btn-secondary"
              @click="cancelOrder(order)"
            >
              取消订单
            </button>
            <button 
              class="btn-outline"
              @click="viewOrderDetail(order)"
            >
              查看详情
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 订单详情模态框 -->
    <div v-if="selectedOrder" class="modal-overlay" @click.self="selectedOrder = null">
      <div class="modal-content">
        <div class="modal-header">
          <h3>订单详情</h3>
          <button class="close-btn" @click="selectedOrder = null">×</button>
        </div>
        <div class="modal-body">
          <div class="detail-section">
            <h4>基本信息</h4>
            <div class="detail-grid">
              <div class="detail-item">
                <span class="label">订单号：</span>
                <span class="value">{{ selectedOrder.id }}</span>
              </div>
              <div class="detail-item">
                <span class="label">景点名称：</span>
                <span class="value">{{ selectedOrder.scenicSpotName }}</span>
              </div>
              <div class="detail-item">
                <span class="label">地址：</span>
                <span class="value">{{ selectedOrder.scenicSpotAddress }}</span>
              </div>
              <div class="detail-item">
                <span class="label">参观日期：</span>
                <span class="value">{{ selectedOrder.visitDate }} {{ selectedOrder.visitTime }}</span>
              </div>
            </div>
          </div>

          <div class="detail-section">
            <h4>游客信息</h4>
            <div v-for="(visitor, index) in selectedOrder.visitors" :key="index" class="visitor-info">
              <div class="detail-item">
                <span class="label">姓名：</span>
                <span class="value">{{ visitor.name }}</span>
              </div>
              <div class="detail-item">
                <span class="label">手机号：</span>
                <span class="value">{{ visitor.phone }}</span>
              </div>
              <div class="detail-item">
                <span class="label">身份证：</span>
                <span class="value">{{ visitor.idCard }}</span>
              </div>
              <div class="detail-item">
                <span class="label">票型：</span>
                <span class="value">{{ visitor.ticketType }}</span>
              </div>
            </div>
          </div>

          <div class="detail-section">
            <h4>费用信息</h4>
            <div class="detail-grid">
              <div class="detail-item">
                <span class="label">单价：</span>
                <span class="value">¥{{ selectedOrder.unitPrice }}</span>
              </div>
              <div class="detail-item">
                <span class="label">数量：</span>
                <span class="value">{{ selectedOrder.visitorCount }}</span>
              </div>
              <div class="detail-item">
                <span class="label">总金额：</span>
                <span class="value price">¥{{ selectedOrder.totalAmount }}</span>
              </div>
              <div v-if="selectedOrder.paymentMethod" class="detail-item">
                <span class="label">支付方式：</span>
                <span class="value">{{ selectedOrder.paymentMethod }}</span>
              </div>
              <div v-if="selectedOrder.paymentTime" class="detail-item">
                <span class="label">支付时间：</span>
                <span class="value">{{ formatDateTime(selectedOrder.paymentTime) }}</span>
              </div>
            </div>
          </div>

          <div v-if="selectedOrder.qrCode" class="detail-section">
            <h4>入园二维码</h4>
            <div class="qr-code">
              <img :src="selectedOrder.qrCode" alt="入园二维码" />
              <p>请出示此二维码入园</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getOrders, getOrderDetail, cancelOrder, payOrder, getOrderStats } from '@/api/orders'

const router = useRouter()

const orders = ref([])
const selectedOrder = ref(null)
const loading = ref(false)
const statusFilter = ref('all')
const stats = ref({})

// 加载订单列表
const loadOrders = async () => {
  loading.value = true
  try {
    const response = await getOrders('user123') // 模拟用户ID
    orders.value = response.data.filter(order => {
      if (statusFilter.value === 'all') return true
      return order.status === statusFilter.value
    })
  } catch (error) {
    console.error('加载订单失败:', error)
  } finally {
    loading.value = false
  }
}

// 加载订单统计
const loadOrderStats = async () => {
  try {
    const response = await getOrderStats('user123')
    stats.value = response.data
  } catch (error) {
    console.error('加载订单统计失败:', error)
  }
}

// 查看订单详情
const viewOrderDetail = async (order) => {
  try {
    const response = await getOrderDetail(order.id)
    selectedOrder.value = response.data
  } catch (error) {
    console.error('加载订单详情失败:', error)
  }
}

// 取消订单
const cancelOrderHandler = async (order) => {
  if (!confirm('确定要取消此订单吗？')) return
  
  try {
    await cancelOrder(order.id)
    alert('订单取消成功')
    loadOrders()
    loadOrderStats()
  } catch (error) {
    console.error('取消订单失败:', error)
    alert('取消订单失败')
  }
}

// 支付订单
const payOrderHandler = async (order) => {
  try {
    const response = await payOrder(order.id, '微信支付')
    if (response.success) {
      alert('支付成功')
      loadOrders()
      loadOrderStats()
    }
  } catch (error) {
    console.error('支付失败:', error)
    alert('支付失败')
  }
}

// 跳转到预约页面
const goToReservation = () => {
  router.push('/reservation')
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    paid: '已支付',
    pending: '待支付',
    cancelled: '已取消'
  }
  return statusMap[status] || status
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 初始化加载
onMounted(() => {
  loadOrders()
  loadOrderStats()
})
</script>

<style scoped>
.my-orders {
  width: 85%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.order-stats {
  margin-bottom: 30px;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  color: white;
}

.order-stats h2 {
  margin: 0 0 20px 0;
  text-align: center;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 20px;
}

.stat-item {
  text-align: center;
  padding: 15px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 8px;
  backdrop-filter: blur(10px);
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  opacity: 0.9;
}

.filter-bar {
  margin-bottom: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
}

.filter-group {
  display: flex;
  align-items: center;
  gap: 10px;
}

.filter-group label {
  font-weight: 500;
}

.filter-group select {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
  background: white;
}

.loading {
  text-align: center;
  padding: 40px;
  color: #666;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #666;
}

.empty-state p {
  margin-bottom: 20px;
  font-size: 16px;
}

.orders-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.order-card {
  background: white;
  border: 1px solid #e0e0e0;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.order-card:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
  transform: translateY(-2px);
}

.order-card.status-paid {
  border-left: 4px solid #28a745;
}

.order-card.status-pending {
  border-left: 4px solid #ffc107;
}

.order-card.status-cancelled {
  border-left: 4px solid #dc3545;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 15px;
}

.order-info h3 {
  margin: 0 0 5px 0;
  color: #333;
  font-size: 18px;
}

.order-id {
  color: #666;
  font-size: 14px;
}

.status-badge {
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 500;
}

.status-paid {
  background: #d4edda;
  color: #155724;
}

.status-pending {
  background: #fff3cd;
  color: #856404;
}

.status-cancelled {
  background: #f8d7da;
  color: #721c24;
}

.order-details {
  margin-bottom: 15px;
}

.detail-item {
  display: flex;
  margin-bottom: 8px;
}

.detail-item .label {
  color: #666;
  min-width: 80px;
  font-size: 14px;
}

.detail-item .value {
  color: #333;
  font-size: 14px;
}

.price {
  color: var(--primary-color);
  font-weight: bold;
  font-size: 16px;
}

.order-actions {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.btn-primary {
  padding: 8px 16px;
  background: var(--primary-color);
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: background 0.3s ease;
}

.btn-primary:hover {
  background: var(--primary-color-dark);
}

.btn-secondary {
  padding: 8px 16px;
  background: #6c757d;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: background 0.3s ease;
}

.btn-secondary:hover {
  background: #5a6268;
}

.btn-outline {
  padding: 8px 16px;
  background: transparent;
  color: var(--primary-color);
  border: 1px solid var(--primary-color);
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
}

.btn-outline:hover {
  background: var(--primary-color);
  color: white;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  padding: 20px;
}

.modal-content {
  background: white;
  border-radius: 12px;
  max-width: 600px;
  width: 100%;
  max-height: 80vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #e0e0e0;
}

.modal-header h3 {
  margin: 0;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #666;
}

.close-btn:hover {
  color: #333;
}

.modal-body {
  padding: 20px;
}

.detail-section {
  margin-bottom: 20px;
}

.detail-section h4 {
  margin: 0 0 15px 0;
  color: #333;
  font-size: 16px;
  border-bottom: 1px solid #eee;
  padding-bottom: 8px;
}

.detail-grid {
  display: grid;
  gap: 12px;
}

.visitor-info {
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
  margin-bottom: 10px;
}

.visitor-info .detail-item {
  margin-bottom: 6px;
}

.qr-code {
  text-align: center;
  padding: 20px;
}

.qr-code img {
  max-width: 200px;
  height: auto;
  margin-bottom: 10px;
}

.qr-code p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

@media (max-width: 768px) {
  .my-orders {
    width: 95%;
    padding: 10px;
  }
  
  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .order-header {
    flex-direction: column;
    gap: 10px;
  }
  
  .order-actions {
    flex-direction: column;
  }
  
  .modal-content {
    margin: 10px;
  }
}
</style>